<template>
    <a-modal v-model:open="open" :title="isEdit ? '编辑卡片' : '新增卡片'" @ok="handleOk" @cancel="handleCancel"
        v-loading="loading">
        <a-form :label-col="labelCol" :wrapper-col="wrapperCol" layout="horizontal" style="max-width: 600px"
            ref="formRef" :model="modelRef" :rules="rules" :loading="loading">
            <a-form-item label="名称" name="card_name">
                <a-input v-model:value="modelRef.card_name" />
            </a-form-item>
            <a-form-item label="余额" name="initial_amount">
                <a-input-number v-model:value="modelRef.initial_amount" />
            </a-form-item>
            <a-form-item label="颜色" name="card_color">
                <!-- 颜色选择 -->
                <a-input type="color" v-model:value="modelRef.card_color" />
            </a-form-item>
            <a-form-item label="图标" name="card_avatar">
                <a-upload v-model:file-list="modelRef.card_avatar" name="file" list-type="picture-card"
                    :headers="headers" :show-upload-list="false" action="http://common.xiaoruan.xyz:3456/upload"
                    :before-upload="beforeUpload" @change="handleChange">
                    <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100px;height: 100px" />
                    <div v-else>
                        <loading-outlined v-if="loading"></loading-outlined>
                        <plus-outlined v-else></plus-outlined>
                        <div class="ant-upload-text">Upload</div>
                    </div>
                </a-upload>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup lang="ts">
import { message, } from "ant-design-vue";
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import type { UploadChangeParam, UploadFile, UploadProps } from 'ant-design-vue';
import { computed, reactive, ref, toRaw, watch, nextTick } from "vue"
import { useMicroGlobalData } from '@/stores/microGlobalData';

import type { Rule } from "ant-design-vue/es/form/interface";
import type { TableDataType } from '../AccountCard.vue'


const labelCol = { style: { width: '100px' } };
const wrapperCol = { span: 14 };

const props = defineProps<{
    show: boolean,
    editData: TableDataType
}>()
const formRef = ref();
const emit = defineEmits(['update:show', 'loadData'])
const store = useMicroGlobalData()
const rules: Record<string, Rule[]> = {
    card_name: [
        { required: true, message: 'Please input Activity name', trigger: 'change' },
    ],
    initial_amount: [{ required: true, message: 'Please select Activity zone', trigger: 'change' }],
    card_color: [{ required: true, message: 'Please pick a date', trigger: 'change' }],
    card_avatar: [
        {
            type: 'array',
            required: true,
            message: 'Please select at least one activity type',
            trigger: 'change',
        },
    ],
};
const modelRef = reactive<Partial<Omit<TableDataType, 'card_avatar'> & { card_avatar: string[] }>>({
    card_name: '',
    initial_amount: "",
    card_color: '',
    card_avatar: Array<string>()
});
const isEdit = ref(false)
const open = ref(false)

watch(() => props.show, async (val) => {
    open.value = val
    await nextTick()
    val && formRef.value.resetFields();
    if (val && Object.keys(props.editData).length > 0) {
        isEdit.value = true
        console.log(props.editData, "props.editData");
        modelRef.card_name = props.editData.card_name
        modelRef.initial_amount = props.editData.current_amount
        modelRef.card_color = props.editData.card_color
        modelRef.card_avatar = [props.editData.card_avatar]
        imageUrl.value = props.editData.card_avatar
    } else {
        isEdit.value = false
        modelRef.card_name = ''
        modelRef.initial_amount = ""
        modelRef.card_color = ''
        modelRef.card_avatar = []
        imageUrl.value = ''
    }
})
const headers = computed(() => {
    const token = store.microGlobalData.storageUtils?.local.get('token') || store.microGlobalData.token
    return {
        Authorization: `Bearer ${token}`
    }
})
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');

const handleChange = (info: UploadChangeParam) => {
    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'done') {
        // Get this url from response in real world.
        loading.value = false;
        imageUrl.value = 'http://common.xiaoruan.xyz:3456/static' + info.file.response?.data.path;
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};
const beforeUpload = (file: UploadFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size! / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

const handleOk = () => {
    formRef.value
        .validate()
        .then(() => {
            console.log('values', toRaw(modelRef));
            isEdit.value ? handleEdit() : handleAdd();
        })
        .catch((error: any) => {
            console.log('error', error);
        });
}
// 新增
const handleAdd = async () => {
    loading.value = true;
    const params = {
        uid: 1,//默认
        ...modelRef,
        initial_amount: modelRef.initial_amount?.toString(),
        current_amount: modelRef.initial_amount?.toString(),
        card_avatar: imageUrl.value
    }
    const res = await store.microGlobalData.axiosInstance?.post<typeof params, string>({ url: '/account/cards', _params: params }, true);
    loading.value = false;
    console.log("🚀 ~ handleAdd ~ res:", res)
    message.success(res);
    emit('update:show', false)
    emit('loadData');
}
const handleEdit = async () => {
    loading.value = true;
    const params = {
        uid: 1,//默认
        ...modelRef,
        initial_amount: props.editData.initial_amount?.toString(),
        current_amount: modelRef.initial_amount?.toString(),
        card_avatar: imageUrl.value
    }
    const res = await store.microGlobalData.axiosInstance?.put<typeof params, string>({ url: '/account/cards/' + props.editData.id, _params: params }, true);
    loading.value = false;
    console.log("🚀 ~ handleAdd ~ res:", res)
    message.success(res);
    emit('update:show', false)
    emit('loadData');
}
const handleCancel = () => {
    emit('update:show', false)
}
</script>

<style lang="scss" scoped></style>